import Hls from 'hls.js';
let that = null
// 获取所有video元素
export function getAllVideo() {
  return document.getElementsByTagName("video");
}
// 加载所有视频
export function loadAllVideo(_that, _isWangEditor) {
  that = _that
  getAllVideo()?.length ? getAllVideo().forEach((ditem) => {
    let dom = ditem;
    if (_isWangEditor) dom.setAttribute('isWangEditor', true)
    if (!dom.attributes["isLoad"] || dom.attributes["isWangEditor"]) {
      listenVideOnload(dom.attributes["id"]?.value);
      dom.setAttribute('isLoad', true)
      setUrlToVideo(dom.attributes[":src"]?.value || dom.attributes["src"]?.value, dom.attributes["id"]?.value, dom);
    }
  }) : false
}
// Hls 加载m3u8资源
export function videoInit(url, domId, dom) {
  var hls = "";
  hls = new Hls();
  hls.loadSource(url);
  hls.attachMedia(document.getElementById(domId));
}
// 设置Video的Url
export function setUrlToVideo(url, domId, dom) {
  if (url.length > 0) {
    if (isUrl(url)) {
      that.$nextTick(() => {
        videoInit(url, domId, dom);
      });
    } else {
      alert("URL不合法");
    }
  }
}
//判断是否为URL
export function isUrl(str) {
  let v = new RegExp(
    "^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$",
    "i"
  );
  return v.test(str);
}
// 监听视频加载情况
export function listenVideOnload(domId) {
  that.$nextTick(() => {
    let video = document.getElementById(domId);
    if (video) {
      video.oncanplay = function () {
        video.pause();
      };
    }
  });
}

export default {
  loadAllVideo,
}